package com.easycar.common.manager;
import com.easycar.common.net.callback.Callback;
import com.easycar.common.util.GLog;
import com.easycar.common.util.GsonUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.HttpRetryException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.security.auth.login.LoginException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 光享网络请求回调
 * @param <T>  泛型
 */

public   abstract   class GCallBack<T>   extends Callback<T> {
    /**
     * Thread Pool Thread
     *
     * @param response
     * @param id
     */
    private static  final  int  SERVER_CODE=-1;
    private Type mGenericSuperclass;

    public GCallBack() {
        Type genericSuperclass = getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            mGenericSuperclass = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
        } else {
            mGenericSuperclass = Object.class;
        }
    }

    /**
     * Thread Pool Thread
     *
     * @param response
     * @param id
     */
    @Override
    public T parseNetworkResponse(Response response, int id) throws Exception {
        String string = response.body().string();
        GLog.e("服务器返回的数据"+string);
        return GsonUtil.getInstance().GsonToBean(string,mGenericSuperclass);
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        String msg="";
        if(e instanceof UnknownHostException ||e instanceof ConnectException){
            msg="网络连接失败，请连接网络....";
        }else if(e instanceof SocketTimeoutException){
            msg="网络请求超时";
        }else if(e instanceof HttpRetryException){
            msg="服务器拒绝请求";
        }else if(e instanceof SocketException){
            msg="网络请求取消";
        }else if(e instanceof LoginException){
            msg=e.getMessage();
        } else {
            msg="网络错误！"+e;
        }
        onError(SERVER_CODE,msg);
    }

    @Override
    public void onResponse(T response, int id) {
         onGResponse(response);
    }

    public  abstract  void onGResponse(T  t );

    public  abstract  void onError(int status,String msg);




}
